package cn.jhc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;

import cn.jhc.Global;
import cn.jhc.bean.Article;
import cn.jhc.db.ArticleDao;

/**
 * Servlet implementation class ListArticlesServlet
 */
@WebServlet("/list.do")
public class ListArticlesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		if(type == null) {
			type = "html";
		}
		String pageNum = request.getParameter("page");
		int currentPage = 0;
		if(pageNum != null) {
			try {
				currentPage = Integer.valueOf(pageNum).intValue();
			} catch (NumberFormatException e1) {
				// TODO: handle exception
				e1.printStackTrace();
				currentPage = 0;
			}
		}
		
		
		QueryRunner runner = (QueryRunner) request.getServletContext().getAttribute(Global.KEY_RUNNER);
		List<Article> articles = null;
		long count = 0;
		try {
			articles = ArticleDao.list(runner, currentPage);
			count = ArticleDao.count(runner);
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		long total = count % Global.PAGE_SIZE == 0 ? count / Global.PAGE_SIZE :
			count / Global.PAGE_SIZE + 1;
		if(type.equals("html")) {
		//session + redirect
		//request.getSession().setAttribute("articles", articles);
		//response.sendRedirect("./list.jsp");
		
		//request + forward
		request.setAttribute("articles", articles);
		request.setAttribute("currentPage", currentPage);
		request.setAttribute("total", total);
		request.getRequestDispatcher("./list.jsp").forward(request, response);
		} else if(type.equals("json")) {
			response.setContentType("application/json; charset=utf8");
			JsonArrayBuilder builder = Json.createArrayBuilder();
			for(Article article : articles) {
				builder.add(article.toJson());
			}
			PrintWriter writer = response.getWriter();
			writer.print(builder.build().toString());
		}
	}

}
